import tkinter as tk
from tkinter import ttk, font
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.dates as mdates
from matplotlib.font_manager import FontProperties
import matplotlib
from tkcalendar import Calendar
import os
import pytz  # 添加这个导入

class StatsView:
    def __init__(self, parent, database):
        self.window = tk.Toplevel(parent)
        self.window.title("每日统计")
        self.window.geometry("900x800")
        self.db = database
        
        # 设置时区
        self.tz = pytz.timezone('Asia/Shanghai')
        
        # 设置全局字体
        self.setup_fonts()
        self.setup_ui()
        self.update_stats()
        
    def setup_fonts(self):
        """设置字体"""
        # 设置matplotlib的字体
        matplotlib.rcParams['font.sans-serif'] = ['SimSun', 'SimHei', 'Microsoft YaHei']
        matplotlib.rcParams['axes.unicode_minus'] = False
        
        # 设置tkinter的字体
        if os.path.exists(r"c:\windows\fonts\simsun.ttc"):
            self.tk_font = ('SimSun', 10)
            self.title_font = ('SimSun', 24, 'bold')
        else:
            self.tk_font = ('TkDefaultFont', 10)
            self.title_font = ('TkDefaultFont', 24, 'bold')

    def setup_ui(self):
        """设置用户界面"""
        # 创建主框架
        main_frame = ttk.Frame(self.window, padding="20")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 标题
        title_label = ttk.Label(main_frame, 
                              text="Practice Statistics",
                              font=('Arial', 24, 'bold'),
                              foreground='#2196F3')
        title_label.pack(pady=(0, 20))
        
        # 上半部分框架（日历和统计数据）
        top_frame = ttk.Frame(main_frame)
        top_frame.pack(fill=tk.X, pady=(0, 20))
        
        # 左侧日历
        calendar_frame = ttk.LabelFrame(top_frame, text="Select Date", padding="10")
        calendar_frame.pack(side=tk.LEFT, fill=tk.BOTH, padx=(0, 10))
        
        self.cal = Calendar(calendar_frame, 
                          selectmode='day',
                          date_pattern='y-mm-dd',
                          showweeknumbers=False,
                          firstweekday='sunday',
                          font=('Arial', 10),
                          selectbackground='#2196F3')
        self.cal.pack(fill=tk.BOTH, expand=True)
        self.cal.bind('<<CalendarSelected>>', self.update_stats)
        
        # 右侧统计数据
        stats_frame = ttk.LabelFrame(top_frame, text="统计数据", padding="15")
        stats_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        
        # 统计数据项（改回中文）
        self.stats_items = [
            ("单词总数", "total_words", "个"),
            ("正确单词", "correct_words", "个"),
            ("错误单词", "wrong_words", "个"),
            ("准确率", "accuracy", "%"),
            ("平均速度", "avg_wpm", "WPM"),
            ("总用时", "total_time", "秒")
        ]
        
        # 创建统计标签
        self.stats_labels = {}
        for i, (label, key, unit) in enumerate(self.stats_items):
            ttk.Label(stats_frame, 
                     text=label,
                     font=('SimSun', 12)).grid(row=i, column=0, sticky='w', pady=5)
            
            value_label = ttk.Label(stats_frame,
                                  text="0",
                                  font=('SimSun', 12, 'bold'))
            value_label.grid(row=i, column=1, padx=10, pady=5)
            
            if unit:
                ttk.Label(stats_frame,
                         text=unit,
                         font=('SimSun', 12)).grid(row=i, column=2, sticky='w', pady=5)
            
            self.stats_labels[key] = value_label
        
        # 图表区域
        chart_frame = ttk.LabelFrame(main_frame, text="Practice Trend", padding="15")
        chart_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 20))
        
        # 创建图表
        self.fig = Figure(figsize=(8, 4), dpi=100)
        self.canvas = FigureCanvasTkAgg(self.fig, master=chart_frame)
        self.canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        
        # 练习记录
        records_frame = ttk.LabelFrame(main_frame, text="Practice Records", padding="15")
        records_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建带滚动条的文本框
        records_container = ttk.Frame(records_frame)
        records_container.pack(fill=tk.BOTH, expand=True)
        
        self.records_text = tk.Text(records_container, 
                                  height=8,
                                  width=70,
                                  font=(self.tk_font[0], 11),
                                  wrap=tk.WORD,
                                  background='#FAFAFA',
                                  borderwidth=1,
                                  relief='solid')
        scrollbar = ttk.Scrollbar(records_container, 
                                orient=tk.VERTICAL,
                                command=self.records_text.yview)
        
        self.records_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(5, 0), pady=5)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y, pady=5)
        
        self.records_text.config(yscrollcommand=scrollbar.set)
        
        # 配置标签样式
        self.records_text.tag_configure('correct', foreground='#4CAF50', font=(self.tk_font[0], 11, 'bold'))
        self.records_text.tag_configure('wrong', foreground='#F44336', font=(self.tk_font[0], 11, 'bold'))
        self.records_text.tag_configure('time', foreground='#757575', font=(self.tk_font[0], 10))
        self.records_text.tag_configure('info', foreground='#616161', font=(self.tk_font[0], 10))
        
        # 确定按钮
        ok_button = ttk.Button(main_frame,
                             text="确定",
                             command=self.window.destroy,
                             width=20)
        ok_button.pack(pady=(10, 0))
    
    def update_stats(self, event=None):
        """更新统计信息"""
        selected_date = self.cal.get_date()
        print(f"Selected date: {selected_date}")
        
        # 获取选中日期的统计数据
        stats = self.db.get_daily_stats(selected_date)
        print(f"Received stats: {stats}")
        
        # 更新统计标签
        if stats:
            for key, label in self.stats_labels.items():
                value = stats.get(key, 0)
                if key == 'avg_wpm':  # 对 WPM 取整
                    value = int(value)  # 或者 round(value)
                elif key == 'accuracy':
                    value = f"{value:.1f}"  # 保持准确率显示一位小数
                label.config(text=str(value))
        else:
            # 如果没有数据，显示 0
            for label in self.stats_labels.values():
                label.config(text="0")
        
        # 更新图表
        self.update_chart()
        self.update_records(selected_date)
    
    def update_chart(self):
        """更新图表"""
        self.fig.clear()
        ax = self.fig.add_subplot(111)
        
        # 获取数据
        dates, total_counts, correct_counts = self.db.get_weekly_stats()
        
        # 转换日期到东八区
        dates = [d.astimezone(self.tz) for d in dates]
        
        # 设置柱状图和折线图
        bars = ax.bar(dates, correct_counts, 
                     color='#4CAF50',
                     alpha=0.6,
                     label='Correct')
        
        line = ax.plot(dates, total_counts, 
                      color='#2196F3',
                      linewidth=2, 
                      marker='o',
                      label='Total')
        
        # 设置标题和标签
        ax.set_title('7-Day Practice Trend', fontsize=12, pad=15)
        ax.set_xlabel('Date', fontsize=10, labelpad=10)
        ax.set_ylabel('Word Count', fontsize=10, labelpad=10)
        
        # 设置x轴格式（使用本地时间）
        date_formatter = mdates.DateFormatter('%m-%d', tz=self.tz)
        ax.xaxis.set_major_formatter(date_formatter)
        self.fig.autofmt_xdate()
        
        # 添加图例（英文）
        ax.legend(loc='upper left')
        
        # 添加网格线
        ax.grid(True, linestyle='--', alpha=0.3)
        
        # 设置y轴从0开始
        ax.set_ylim(bottom=0)
        
        # 在柱状图顶部添加数值标签
        for bar in bars:
            height = bar.get_height()
            if height > 0:
                ax.text(bar.get_x() + bar.get_width()/2., height,
                       f'{int(height)}',
                       ha='center', va='bottom',
                       fontsize=9)
        
        # 在折线图的点上添加数值标签
        for x, y in zip(dates, total_counts):
            if y > 0:
                ax.text(x, y, f'{int(y)}',
                       ha='center', va='bottom',
                       fontsize=9)
        
        # 调整布局
        self.fig.tight_layout()
        
        # 重绘图表
        self.canvas.draw()
    
    def update_records(self, selected_date):
        """更新练习记录"""
        records = self.db.get_daily_records(selected_date)
        
        self.records_text.config(state='normal')
        self.records_text.delete('1.0', tk.END)
        
        for record in records:
            word, pos, meaning, is_correct, typing_time, wpm, practice_time = record
            status = "✓" if is_correct else "✗"
            color = '#4CAF50' if is_correct else '#F44336'
            
            # 使用 tag 来设置颜色
            tag_name = f"color_{len(self.records_text.tag_names())}"
            self.records_text.tag_configure(tag_name, foreground=color, font=(self.tk_font[0], 11, 'bold'))
            
            # 插入记录
            self.records_text.insert('end', f"{practice_time} - ", 'normal')
            self.records_text.insert('end', f"{status} {word}", tag_name)
            self.records_text.insert('end', 
                f"\n    词性：{pos}\n"
                f"    含义：{meaning}\n"
                f"    用时：{typing_time:.1f}秒, WPM：{wpm}\n"
                f"{'='*50}\n",
                'normal'
            )
        
        self.records_text.config(state='disabled')
